package com.iflytek.uoamp.agent.common.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

public class HttpHelper {

	private HttpClient httClient = new HttpClient();
	private Lock lock = new ReentrantLock();


	/**
	 * http 的 post 方法;本项目中应用于以HTTP方式与 MCServer 通信的时候
	 * @param url			接口名称
	 * @param head			参数
	 * @param requestData	请求体
	 * @param responseData	响应体
	 * @param encoding		请求编码
	 * @param timeOut		请求超时时间
	 * @return
	 */
	public boolean post(String url, String head,String requestData, StringBuffer responseData, String encoding, int timeOut) {
		PostMethod method = new PostMethod(url);

		httClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
		httClient.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
		httClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
		method.addRequestHeader("Connection", "close");
		method.addRequestHeader("monitortype", head);
		method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);

		try {
			// method.setRequestBody(requestData);
			byte[] content = EncryptHelper.desEncrypt(requestData.getBytes("utf-8"), "x%73g-07".getBytes("utf-8"));
			method.setRequestEntity(new ByteArrayRequestEntity(content));
			lock.lock();
			try{
				httClient.executeMethod(method);
			}finally{
				lock.unlock();
			}
			InputStream in = null;
			ByteArrayOutputStream out = null;
			in = method.getResponseBodyAsStream();

			if (in != null) {
				byte[] buffer = new byte[1024];
				int bufferFilled = 0;
				out = new ByteArrayOutputStream();
				while ((bufferFilled = in.read(buffer, 0, buffer.length)) != -1) {
					out.write(buffer, 0, bufferFilled);
				}

				byte[] responseBody = EncryptHelper.desDecrypt(out.toByteArray(), "x%73g-07".getBytes("utf-8"));
				responseData.append(new String(responseBody,"utf-8"));

			}

		} catch (Exception e) {
			Logger.getRootLogger().error("fail url is "+url+" and request data is "+requestData,e);
			return false;
		} finally {
			method.releaseConnection();
		}

		return true;
	}

	/***
	 * 使用post方法请求服务器
	 * @param url				需要请求的地址
	 * @param requestData		需要请求的数据包
	 * @param responseData		返回的数据将写到这个参数中
	 * @param encoding			期望服务器返回时使用的编码
	 * @param timeOut			等待服务器超时的时间（等待连接和等待数据传输使用时间相同）
	 * @return
	 */
	public boolean post(String url, byte[] requestData, StringBuffer responseData, String encoding, int timeOut) {
		PostMethod method = new PostMethod(url);

		httClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
		httClient.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
		httClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
		method.addRequestHeader("Connection", "close");
		method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);

		try {
			method.setRequestEntity(new ByteArrayRequestEntity(requestData));
			lock.lock();
			try{
				httClient.executeMethod(method);
			}finally{
				lock.unlock();
			}
			InputStream in = null;
			ByteArrayOutputStream out = null;
			in = method.getResponseBodyAsStream();

			if (in != null) {
				byte[] buffer = new byte[1024];
				int bufferFilled = 0;
				out = new ByteArrayOutputStream();
				while ((bufferFilled = in.read(buffer, 0, buffer.length)) != -1) {
					out.write(buffer, 0, bufferFilled);
				}

				responseData.append(new String(out.toByteArray(),encoding));

			}

		} catch (Exception e) {
			Logger.getRootLogger().error("fail url is "+url,e);
			return false;
		} finally {
			method.releaseConnection();
		}

		return true;
	}

}